package com.nuoniu.sibanyun.service.crm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SysCompany;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.SysUserRole;
import com.nuoniu.sibanyun.entity.crm.CrmGoods;
import com.nuoniu.sibanyun.entity.crm.CrmGoodsCallSetting;
import com.nuoniu.sibanyun.entity.crm.bo.GoodsOrderDetailBo;
import com.nuoniu.sibanyun.entity.crm.dto.CrmGoodsSaveDto;
import com.nuoniu.sibanyun.mapper.SysCompanyMapper;
import com.nuoniu.sibanyun.mapper.SysUserMapper;
import com.nuoniu.sibanyun.mapper.SysUserRoleMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmGoodsMapper;
import com.nuoniu.sibanyun.service.crm.ICrmGoodsCallSettingService;
import com.nuoniu.sibanyun.service.crm.ICrmGoodsService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 客户商品表 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2020-07-17
 */
@Service
public class CrmGoodsServiceImpl extends ServiceImpl<CrmGoodsMapper, CrmGoods> implements ICrmGoodsService {

    @Autowired
    private SysCompanyMapper companyMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ICrmGoodsCallSettingService goodsCallSettingService;

    @Override
    public List<CrmGoods> pageGoods(Page pages, CrmGoods goods) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<CrmGoods> queryWrapper = new QueryWrapper<>();
        String goodsType = goods.getGoodsType();
        if(StringUtils.isNotBlank(goodsType)){
            queryWrapper.eq("goods_type", goodsType);
        }
        if(StringUtils.isNotBlank(goods.getGoodsName())) {
            queryWrapper.like("goods_name", goods.getGoodsName());
        }

        if(goods.getStatus() != null) {
            queryWrapper.eq("status", goods.getStatus());
        }

        if(goods.getIsReward() != null) {
            queryWrapper.eq("is_reward", goods.getIsReward());
        }

        if(userInfo.getCompanyId() != null && !userInfo.getCompanyId().equals(1)) {
            queryWrapper.eq("status", 0);
        }

        queryWrapper.orderByAsc("sort");
        return list(queryWrapper);
    }

    @Override
    public List<GoodsOrderDetailBo> pageGoodsSetting(Page page) {
        List<GoodsOrderDetailBo> goodsOrderDetailBos = baseMapper.pageGoodsSetting(page);
        return goodsOrderDetailBos;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveGoods(CrmGoodsSaveDto crmGoodsSaveDto) {
        String goodsType = crmGoodsSaveDto.getGoodsType();
        if(StringUtils.isBlank(goodsType))throw new NuoNiuException("参数错误");
        CrmGoods goods = new CrmGoods();
        BeanUtils.copyProperties(crmGoodsSaveDto,goods);
        switch (goodsType){
            /** 软件 */
            case "software":
                if(crmGoodsSaveDto.getRoleId() == null) {
                    throw new NuoNiuException("角色不能为空");
                }
                if(crmGoodsSaveDto.getRoleId().equals(1)) {
                    throw new NuoNiuException("不能使用超级管理员");
                }
                this.saveOrUpdate(goods);
                break;
            /** 话费 */
            case "telCharges":
                this.saveOrUpdate(goods);
                CrmGoodsCallSetting callSetting = goodsCallSettingService.getByGoodsId(goods.getId());
                if(null == callSetting)callSetting = new CrmGoodsCallSetting();
                callSetting.setCrmGoodsId(goods.getId().intValue());
                callSetting.setMinutePrice(crmGoodsSaveDto.getMinutePrice());
                callSetting.setBaseMinutes(crmGoodsSaveDto.getBaseMinutes());
                callSetting.setIsSetting(crmGoodsSaveDto.getIsSetting());
                goodsCallSettingService.saveOrUpdate(callSetting);
        }

    }

    @Override
    public void useGoods(Long id) {
        UserInfo userInfo = UserThreadLocal.get();
        CrmGoods goods = this.getById(id);
        if(goods == null || goods.getRoleId() == null || userInfo.getUserId().equals(1)) {
            throw new NuoNiuException("使用失败,请联系管理员");
        }

        SysCompany company = companyMapper.selectById(userInfo.getCompanyId());
        if(company != null && company.getId() != 1) {
            Integer roleId = 9;
            SysUserRole userRole = new SysUserRole();
            company.setGoodsId(id.intValue());
            companyMapper.updateById(company);

            if(company.getGoodsId() != null) {
                CrmGoods cGoods = this.getById(id);
                if(cGoods != null) {
                    roleId = cGoods.getRoleId();
                }
            }

            SysUser user =  userMapper.getSysManager(userInfo.getCompanyId(), roleId);
            //删除之前的管理员角色
            if(user != null) {
                userRole.setUserId(user.getId());
                userRoleMapper.deleteByUserId(user.getId());
            } else {
                userRole.setUserId(userInfo.getUserId().longValue());
                userRoleMapper.deleteByUserId(userInfo.getUserId().longValue());
            }

            //切换管理员角色
            userRole.setRoleId(goods.getRoleId().longValue());
            userRoleMapper.insert(userRole);
        }

    }

    @Override
    public Integer getCompanySysRoleIdByCompanyId() {
        UserInfo userInfo = UserThreadLocal.get();
        CrmGoods crmGoods = baseMapper.getCrmGoodsByCompanyId(userInfo.getCompanyId());
        if(null == crmGoods){
            return 2;
        }
        return crmGoods.getRoleId();
    }

    @Override
    public boolean isHaveOperationRight(Long checkUserId) {
        Integer companySysRoleIdByCompanyId = getCompanySysRoleIdByCompanyId();
        UserInfo userInfo = UserThreadLocal.get();
        //如果是租户管理员，可直接赋予权限
        if (userInfo.getRoleIds().contains(companySysRoleIdByCompanyId)){
            return true;
        }
        if(null != checkUserId && checkUserId.toString().equals(userInfo.getUserId().toString())){
            return true;
        }
        return false;
    }

    @Override
    public Integer getCountByRoleId(Long id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("role_id", id);
        return this.count(wrapper);
    }
}
